package com.xiaoq.baiduunit.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xiaoq.UnitProperties;
import com.xiaoq.baiduunit.util.HttpUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 获取token类
 */
@Service
public class UnitService {

    @Autowired
    private UnitProperties unitProperties;

    public String getUnitAccessToken(String unitAppKey, String unitAppSecret) throws RuntimeException{
        if(StringUtils.isBlank(unitAppKey) || StringUtils.isBlank(unitAppSecret)){
            return null;
        }

        String tokenString = unitProperties.getTokenAuthUrl() + "?"
                + "grant_type=client_credentials"
                + "&client_id=" + unitAppKey
                + "&client_secret=" + unitAppSecret;
        try {
            String result = HttpUtil.get(tokenString);
            JSONObject jsonObject = JSON.parseObject(result);
            String accessToken = jsonObject.getString("access_token");
            return accessToken;
        } catch (Exception e) {
            new RuntimeException("获取token失败！");
        }
        return null;
    }

    public String getUnitResponseString(String accessToken, String query, String sessionId
                        ,String seceneId) throws Exception{
        if(StringUtils.isBlank(accessToken) || StringUtils.isBlank(seceneId)){
            return null;
        }

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("scene_id", seceneId);
        paramMap.put("query", query);
        paramMap.put("session_id", sessionId);
        String paramString = JSON.toJSONString(paramMap);
        String result = HttpUtil.post(unitProperties.getUnitTalkUrl(), accessToken, "application/json", paramString);
        return result;
    }

    public String getWeatherResponseString(String city) throws Exception{
        if(StringUtils.isBlank(city)){
            return null;
        }
        String weartherUrl = unitProperties.getWeatherApiUrl() + "?location="+city
                +"&output=json&ak="+unitProperties.getWeatherApiAk();
        String result = HttpUtil.get(weartherUrl);
        return result;
    }

}